package com.huluobo.a2207mmonthdemo.login;


import android.content.Intent;
import android.util.Log;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2207mmonthdemo.MainActivity;
import com.huluobo.a2207mmonthdemo.R;
import com.huluobo.a2207mmonthdemo.databinding.ActivityLoginBinding;
import com.huluobo.base.bean.Money;
import com.huluobo.base.db.AppDbUtils;
import com.huluobo.base.mvvm.BaseMVVMActivity;
import com.huluobo.base.net.Const;

public class LoginActivity extends BaseMVVMActivity<ActivityLoginBinding, LoginViewModel> {

    @Override
    protected void initData() {
        vm.loginSuccess.observe(this, userBeanResult -> {
            if (userBeanResult.getCode() == 200) {
                ToastUtils.showLong("欢迎回来:" + userBeanResult.getData().getUsername());
                SPUtils.getInstance().put(Const.PARAM_TOKEN, userBeanResult.getData().getToken());
                SPUtils.getInstance().put(Const.PARAM_USERNAME, userBeanResult.getData().getUsername());
                Money money = new Money(10000L, userBeanResult.getData().getUsername());
                AppDbUtils.getInstance().getMoneyDao().insertMoneyInfo(money);
                AppDbUtils.getInstance().getUserDao().insertUserInfo(userBeanResult.getData());
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
            } else {
                ToastUtils.showLong(userBeanResult.getMessage());
            }
        });

        vm.loginFailed.observe(this, s -> {
            Log.i("TagA", "登录失败:" + s);
        });
    }

    @Override
    protected void initView() {
        binding.loginBtn.setOnClickListener(v -> {
            String username = binding.loginUsernameEt.getText().toString();
            String password = binding.loginPasswordEt.getText().toString();
            if (username.isEmpty() || password.isEmpty()) {
                ToastUtils.showLong("用户名或密码不能为空");
            } else {
                vm.login(username, password);
            }
        });
    }

    @Override
    protected Class<LoginViewModel> getViewModel() {
        return LoginViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }
}